//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	CamlQueryBuilderInItem.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System.Linq;
using Microsoft.SharePoint;

namespace Smart.Common.Entities
{
	public class CamlQueryBuilderInItem<TExecutorType> : CamlQueryBuilderConditionItem<TExecutorType>
		where TExecutorType : class
	{
		/// <summary>
		/// Values
		/// </summary>
		public string[] Values { get; set; }

		public CamlQueryBuilderInItem(string field, string valueType, params string[] values)
			: base(field, "In", valueType, null)
		{
			Values = values;
		}

		/// <summary>
		/// Return Cache code
		/// </summary>
		public override int GetCacheCode()
		{
			return
				base.GetCacheCode() ^
				Values.Aggregate(0, (accu, value) => accu ^ value.GetHashCode());
		}

		/// <summary>
		/// Format QueryBuilder statement
		/// </summary>
		public override string FormatQuery()
		{
			var isLookup = false;
			string fieldName = null;

			if (Query != null)
			{
				var mf = Query.Meta.Field(Field);

				if (mf != null)
				{
					fieldName = mf.Name;

					isLookup = (mf.Type == SPFieldType.Lookup || mf.Type == SPFieldType.User);
				}
			}

			if (fieldName == null)
				fieldName = Field;

			var lookup = string.Empty;

			if (isLookup && ValueType.EqIC("Integer"))
			{
				lookup = " LookupID=\"TRUE\"";
				ValueType = "Lookup";
			}
			else if (fieldName.EqIC(SN.IDField) && ValueType.EqIC("Integer"))
			{
				ValueType = "Counter";
			}

			if (Values.Length <= 0)
				return string.Empty;

			if (Values.Length == 1)
				return
					string.Format("<{0}><FieldRef Name=\"{1}\"{3}/>{2}</{0}>", "Eq", fieldName, "<Value Type=\"" + ValueType + "\">" + Values[0].EncodeXml() + "</Value>", lookup);

			return
				string.Format("<{0}><FieldRef Name=\"{1}\"{3}/><Values>{2}</Values></{0}>", Op, fieldName,
							  Values.CastToString(string.Empty, value => "<Value Type=\"" + ValueType + "\">" + value.EncodeXml() + "</Value>"), lookup);
		}
	}
}